import config from '@/config'
import path from 'path'
import { createLogger, format, transports } from 'winston'
import DailyRotateFile from 'winston-daily-rotate-file'
import chalk from 'chalk'

/**
 * 全局日志记录器
 */
export const globalLogger = {
  server: createGlobalLogger({ prefix: 'server' }),
  send: createGlobalLogger({ prefix: 'send' }),
  encrypt: createGlobalLogger({ prefix: 'encrypt' })
}

/**
 * 创建项目日志记录器
 * @param options
 */
export function createProjectLogger(options: ProjectLoggerOptions) {
  const logger = createLogger({
    level: 'info',
    format: customFormat(),
    transports: [createDailyRotateFile({ filename: path.resolve(options.dir, '%DATE%.log') })]
  })

  if (config.isDev) {
    logger.add(transports_console())
  }

  return logger
}

export interface ProjectLoggerOptions {
  dir: string
}

function createGlobalLogger(options: GlobalLoggerOptions) {
  const logger = createLogger({
    level: 'info',
    format: customFormat(),
    transports: [
      createDailyRotateFile({
        filename: path.resolve(config.globalLogDir, options.prefix + '-%DATE%.log')
      })
    ]
  })

  if (config.isDev) {
    logger.add(transports_console())
  }

  return logger
}

interface GlobalLoggerOptions {
  prefix: string
}

function transports_console() {
  return new transports.Console({
    level: 'warn',
    format: format.combine(
      format.colorize(),
      format.printf((i) => `${chalk.dim(i.timestamp)} ${i.level}: ${i.message || i.stack}`)
    )
  })
}

function createDailyRotateFile(options: DailyRotateFile.DailyRotateFileTransportOptions) {
  const _options: DailyRotateFile.DailyRotateFileTransportOptions = {
    datePattern: 'YYYY-MM-DD',
    zippedArchive: true,
    maxSize: '20m', // 每个日志文件的最大大小
    maxFiles: '14d' // 保留最近 14 天的日志文件
  }

  Object.assign(_options, options)

  return new DailyRotateFile(_options)
}

function customFormat() {
  return format.combine(
    format.errors({ stack: true }), // <- 处理 Error 对象
    format.timestamp({ format: 'HH:mm:ss' }),
    format.printf((info) => `${info.timestamp} ${info.level}: ${info.message || info.stack}`)
  )
}
